package com.czt.mail.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * @author czt
 * @version 1.0
 * {@desc}
 * @date 2024/10/8 16:14
 */
public class ConsumerQuickStart {
    public static void main(String[] args) {

        //1.连接信息
        Properties properties = new Properties();
        //连接信息
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        //消费者组，同一个组中只能有一个消费者能够收到消息，其他的都收不到；如果希望多个消费者都能收到消息，需要配置不同的组如-group2
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group");
        //key序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //value序列化
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        //2.创建对象
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(properties);

        //3.订阅主题
        kafkaConsumer.subscribe(Collections.singletonList("topic"));
        //4.获取消息
        while (true) {
            ConsumerRecords<String, String> poll = kafkaConsumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> consumerRecord : poll) {
                System.out.println("consumerRecord-key = " + consumerRecord.key());
                System.out.println("consumerRecord-value = " + consumerRecord.value());
            }
        }
    }
}
